<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="contractYear">
        <el-date-picker
          v-model="queryParams.contractYear"
          type="year"
          placeholder="选择年"
          format="YYYY年"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="queryParams.supplierId"
          placeholder="请选择供应商"
          clearable
          filterable
          size="small"
        >
          <el-option
            v-for="dict in supplierIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-no-more-click type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button v-no-more-click icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="季度统计" name="first">
        <el-table v-loading="loading" :data="quarterList">
          <el-table-column label="季度" align="center" prop="contractQuarter" />
          <el-table-column label="物料名称" align="center" prop="materialName" />
          <el-table-column label="采购金额" align="center" prop="purchaseAmount" />
          <el-table-column label="退款金额" align="center" prop="returnAmount" />
          <el-table-column label="采购数量" align="center" prop="purchaseNum" />
          <el-table-column label="到货数量" align="center" prop="arriveNum" />
          <el-table-column label="入库数量" align="center" prop="inWarehouseNum" />
          <el-table-column label="退货数量" align="center" prop="returnNum" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="月份统计" name="second">
        <el-table v-loading="loading" :data="monthList">
          <el-table-column label="月份" align="center" prop="contractMonth" />
          <el-table-column label="物料名称" align="center" prop="materialName" />
          <el-table-column label="采购金额" align="center" prop="purchaseAmount" />
          <el-table-column label="退款金额" align="center" prop="returnAmount" />
          <el-table-column label="采购数量" align="center" prop="purchaseNum" />
          <el-table-column label="到货数量" align="center" prop="arriveNum" />
          <el-table-column label="入库数量" align="center" prop="inWarehouseNum" />
          <el-table-column label="退货数量" align="center" prop="returnNum" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { monthReport, quarterReport } from '@/api/purchaseReport/contractArriveReturnReport'
import { getQueryData } from '@/api/query/comQuery'

// 响应式状态
const activeName = ref('first')
const loading = ref(true)
const showSearch = ref(true)
const queryForm = ref(null)
const supplierIdOptions = ref([])
const monthList = ref([])
const quarterList = ref([])

// 初始化当前年份
const currentYear = ref(new Date().getFullYear().toString())

// 查询参数（移除分页相关字段）
const queryParams = reactive({
  supplierId: undefined,
  contractYear: currentYear.value,
  contractQuarter: undefined,
  materialId: undefined,
  materialName: undefined
  // 已移除 pageNum 和 pageSize
})

// 生命周期钩子
onMounted(async () => {
  try {
    await Promise.all([getList(), fetchSupplierOptions()])
  } catch (error) {
    ElMessage.error('初始化数据失败')
  }
})

// 获取供应商选项
const fetchSupplierOptions = async () => {
  try {
    const res = await getQueryData("query_supplier", {})
    supplierIdOptions.value = res.data
  } catch (error) {
    ElMessage.error('获取供应商选项失败')
  }
}

// 获取报表数据
const getList = async () => {
  try {
    loading.value = true
    // 创建净化后的查询参数（保留空字符串）
    const cleanParams = Object.fromEntries(
      Object.entries(queryParams)
        .filter(([_, v]) => v !== undefined) // 仅过滤undefined
    )
    
    // 修改接口调用方式（添加参数强制获取全部数据）
    const [monthRes, quarterRes] = await Promise.all([
      monthReport({ 
        ...cleanParams,
        pageNum: 1,     // 如果接口强制需要分页参数
        pageSize: 1000  // 设置足够大的分页尺寸
      }),
      quarterReport({
        ...cleanParams,
        pageNum: 1,
        pageSize: 1000
      })
    ])
    
    // 直接取data数组（根据实际接口返回结构调整）
    monthList.value = monthRes.data || monthRes.rows
    quarterList.value = quarterRes.data || quarterRes.rows
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 搜索操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryForm.value.resetFields()
  queryParams.contractYear = currentYear.value
  nextTick(() => handleQuery())
}
</script>
